<template>
  <view class="family-info-form">
    <!-- 使用通用展示组件 -->
    <DetailDisplayList
      :config="config"
      :list="familyList"
      :loading="loading"
      @add="handleAddFamily"
      @delete="handleDeleteFamily"
    />

    <!-- 新增家庭成员弹窗 -->
    <XenUnifiedAddPopup
      v-model:show="showAddPopup"
      :config="familyPopupConfig"
      :person-id="props.personId"
      :on-submit="handleFamilySubmit"
      @confirm="handleAddSuccess"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import useActivityApi from "../../api/index";
import type {
  GetFamilyResponse,
  ISysPersonFamilyVm,
  ISysPersonFamily,
} from "../../api/interface";
import XenUnifiedAddPopup from "./XenUnifiedAddPopup.vue";
import DetailDisplayList from "./DetailDisplayList.vue";
import { familyConfig } from "./popupConfigs";
import { familyDisplayConfig } from "./detailDisplayConfig";

const api = useActivityApi();

// Props
interface Props {
  personId?: string;
}

const props = withDefaults(defineProps<Props>(), {
  personId: "",
});

// 数据
const loading = ref(false);
const familyList = ref<GetFamilyResponse[]>([]);
const showAddPopup = ref(false);

// 弹框配置
const familyPopupConfig = ref(familyConfig);

// 详情展示配置
const config = ref(familyDisplayConfig);

// 处理家庭成员提交
const handleFamilySubmit = async (formData: any) => {
  const requestData: ISysPersonFamilyVm = {
    Entity: {
      ...formData,
      PersonId: props.personId,
    } as unknown as ISysPersonFamily,
  };

  await api.addFamily(requestData);
};

// 加载家庭成员列表
const loadFamilyList = async () => {
  if (!props.personId) {
    console.log("家庭成员组件：缺少personId");
    return;
  }

  loading.value = true;

  try {
    const requestData = {
      Limit: 50,
      Page: 1,
      PersonId: props.personId,
      SortInfo: null,
    };

    console.log("家庭成员组件：获取家庭成员请求参数:", requestData);
    const res = await api.getFamily(requestData);
    console.log("家庭成员组件：家庭成员接口返回:", res);

    if (res && res.Data && Array.isArray(res.Data)) {
      familyList.value = res.Data;
      console.log("家庭成员组件：获取家庭成员成功:", familyList.value);
    } else {
      familyList.value = [];
      console.log("家庭成员组件：家庭成员数据为空");
    }
  } catch (error) {
    console.error("家庭成员组件：获取家庭成员异常:", error);
    familyList.value = [];
    uni.showToast({
      title: "获取家庭成员失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 处理新增家庭成员
const handleAddFamily = () => {
  if (!props.personId) {
    uni.showToast({
      title: "缺少人员信息",
      icon: "none",
    });
    return;
  }

  showAddPopup.value = true;
};

// 处理删除家庭成员
const handleDeleteFamily = (item: GetFamilyResponse) => {
  uni.showModal({
    title: "确认删除",
    content: `确定要删除家庭成员"${item.MemberName || "未知成员"}"吗？`,
    confirmText: "删除",
    confirmColor: "#ef4444",
    cancelText: "取消",
    success: async (res) => {
      if (res.confirm) {
        await deleteFamily(item.ID);
      }
    },
  });
};

// 删除家庭成员
const deleteFamily = async (id: string) => {
  try {
    uni.showLoading({
      title: "删除中...",
    });

    await api.deleteFamily([id]);

    uni.hideLoading();
    uni.showToast({
      title: "删除成功",
      icon: "success",
    });

    // 刷新列表
    loadFamilyList();
  } catch (error) {
    uni.hideLoading();
    console.error("删除家庭成员失败:", error);
    uni.showToast({
      title: "删除失败，请重试",
      icon: "none",
    });
  }
};

// 处理新增成功
const handleAddSuccess = () => {
  console.log("新增家庭成员成功，刷新列表");
  loadFamilyList();
};

// 监听personId变化，加载家庭成员
watch(
  () => props.personId,
  (newId) => {
    if (newId) {
      loadFamilyList();
    }
  },
  { immediate: true },
);

// 暴露方法供父组件调用
defineExpose({
  loadFamilyList,
});
</script>

<!-- 家庭成员组件不需要自定义样式，完全使用通用组件 -->
